from functools import lru_cache
from pytmx import load_pygame

from settings import *


class SpriteManager(object):
    __instance = None
    __init_flag = True

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self):
        if self.__init_flag:
            self.levels = {}
            self.groups = {}
            self.base_sprites_cls = {}
            self.sprites_cls = {}
            self.statics = {}
            self.events = {}
            self.player_cls = []
            self.players = {}
            self.enemy_cls = []
            self.tmx_data = None

    def setup(self):
        print("manager setup .....")
        self.tmx_data = load_pygame('./data/pimap.tmx')

    def set_event(self, name, event):
        self.events[name] = event

    def get_event(self, name):
        return self.events[name]

    def set_level(self, name, level):
        self.levels[name] = level

    def get_level(self, name):
        return self.levels[name]

    def set_static(self, name, static):
        self.statics[name] = static

    def get_static(self, name):
        return self.statics[name]

    def set_group(self, name, group):
        self.groups[name] = group

    def get_group(self, name) -> PG.sprite.Group:
        return self.groups[name]

    def create_player(self, index, *args, name="player", **kwargs):
        if not self.players.get(name):
            player = self.player_cls[index](name, *args, **kwargs)
            self.players[name] = player
        return self.players[name]

    def get_player(self, name="player"):
        return self.players.get(name)

    def create_enemy(self, index, *args, **kwargs):
        enemy = self.enemy_cls[index](*args, **kwargs)
        return enemy

    @lru_cache
    def tmx_load_by_name(self, name):
        return self.tmx_data.get_layer_by_name(name)


sprite_mgr = SpriteManager()
sprite_mgr.setup()
